// app.js
App({
  data: {
    root: 'https://www.zxgxk.com/v1',//后端正式版

    // root: 'http://127.0.0.1:7439/v1',
    // root: 'https://xk.sumixer.com/',
    // slhroot: 'https://slhxk.sumixer.com/'
    // slhroot: 'https://xk.lou-yy.com/',
  },
  onLaunch() {
    //云开发初始化
    wx.cloud.init({   
      env: 'zhixin-cloud-8gmkon9vea6aff6a',
      traceUser: true
      })

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })

    //获取openid
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        console.log('云函数获取到的openid: ', res.result.openId)
        var openid = res.result.openId;

        const watcher = wx.cloud.database().collection('Message')
        .where({
        id:openid
        })
        // 发起监听
        .watch({
          onChange: function(snapshot) {
            console.log('snapshot', snapshot)
            if(snapshot.docChanges[0].dataType == 'add'){
              wx.showModal({
                title: '提示',
                content: '有新的问题,是否前往查看？',
                success: function (res) {
                  if (res.confirm) {//这里是点击了确定以后
                    wx.navigateTo({
                      url: '../post/post?id=' + snapshot.docChanges[0].doc.postid
                    })
                  } else {//这里是点击了取消以后
                    console.log('用户点击取消')
                  }
                }
              })
            }
          },
          onError: function(err) {
            console.error('the watch closed because of error', err)
          }
        })
      }
    })
  }
})
